package com.jacen.fzxs.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.jacen.fzxs.entity.RightEntity;
import com.jacen.fzxs.entity.RoleEntity;
import com.jacen.fzxs.entity.RoleRightEntity;
import com.jacen.fzxs.service.IRightService;
import com.jacen.fzxs.service.IRoleRightService;
import com.jacen.fzxs.service.IRoleService;
import com.jacen.fzxs.util.TreeNode;
import com.jacen.fzxs.util.Utils;

/**
 * 角色权限控制
 * @author Jacen
 *
 */
@Controller
public class RoleRightController extends BaseController {
	
	@Resource
	private IRoleRightService roleRightService;
	@Resource
	private IRightService rightService;
	@Resource
	private IRoleService roleService;
	
	@RequestMapping("/roleright/list.do")
	public String list(HttpServletRequest request,ModelMap modelMap,String id){
		List<RoleRightEntity> list = roleRightService.getAll();
		modelMap.put("list", list);
		return "roleright/list";
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/roleright/update.do")
	@ResponseBody
	public String postConfig(String id,String select,ModelMap modelMap){
		try{
			roleRightService.updateRightByRole(id,select);
			return Utils.normalJsonResp();
		}catch(Exception e){
			return Utils.errorJsonResp("更新角色权限异常");
		}
	}
	
	@RequestMapping(method=RequestMethod.GET,value="/roleright/update.do")
	public String config(String id,ModelMap modelMap){
		RoleEntity entity = roleService.getById(id);
		List<RightEntity> list = rightService.getListByUpId("1");
		List<String> hasList = rightService.getIdsByRole(id);
		modelMap.put("role", entity);
		modelMap.put("rightJson", toTreeBeanListJson(list,hasList));
		return "roleright/update";
	}
	
	private String toTreeBeanListJson(List<RightEntity> list,List<String> hasList){
		List<TreeNode> treeBeans = new ArrayList<TreeNode>();
		TreeNode bean = new TreeNode();
		bean.setId("1");
		bean.setName("系统权限");
		bean.setOpen(true);
		bean.setUrl("right/list.do?pid=1");
		bean.setTarget("rightList");
		treeBeans.add(bean);
		for(RightEntity entity : list){
			bean = new TreeNode();
			bean.setId(entity.getId());
			bean.setPId(entity.getUpRightId());
			bean.setName(entity.getRightName());
			if(hasList.contains(entity.getId())){
				bean.setChecked(true);
			}
			bean.setOpen((entity.getOpen()==null||entity.getOpen()==0)?false:true);
			treeBeans.add(bean);
		}
		return JSON.toJSONString(treeBeans);
	}
	
	

}
